<?php
namespace app\api\controller;

use app\common\controller\BaseController;
use support\Request;
use support\Db;
use support\Log;

/**
 * 开发测试控制器
 * 用于处理自定义参数保存和传递测试
 */
class TestController extends BaseController
{
    /**
     * 保存自定义测试参数
     */
    public function saveCustomParams(Request $request)
    {
        $userId = $request->userId;
        $params = $request->post('params');
        $appId = $request->post('app_id');
        $paramName = $request->post('param_name', 'default');
        
        if (empty($params)) {
            return json(['code' => 400, 'msg' => '参数不能为空']);
        }
        
        // 验证参数格式
        if (!is_array($params)) {
            return json(['code' => 400, 'msg' => '参数格式错误']);
        }
        
        try {
            Db::beginTransaction();
            
            // 检查是否已存在同名参数
            $existing = Db::table('gf_test_custom_params')
                ->where('user_id', $userId)
                ->where('app_id', $appId)
                ->where('param_name', $paramName)
                ->first();
                
            if ($existing) {
                // 更新现有参数
                Db::table('gf_test_custom_params')
                    ->where('id', $existing->id)
                    ->update([
                        'params' => json_encode($params),
                        'updated_at' => date('Y-m-d H:i:s')
                    ]);
                    
                $paramId = $existing->id;
            } else {
                // 创建新参数
                $paramId = Db::table('gf_test_custom_params')->insertGetId([
                    'user_id' => $userId,
                    'app_id' => $appId,
                    'param_name' => $paramName,
                    'params' => json_encode($params),
                    'created_at' => date('Y-m-d H:i:s'),
                    'updated_at' => date('Y-m-d H:i:s')
                ]);
            }
            
            Db::commit();
            
            Log::info("Custom test parameters saved", [
                'user_id' => $userId,
                'app_id' => $appId,
                'param_name' => $paramName,
                'param_id' => $paramId
            ]);
            
            return json([
                'code' => 200,
                'msg' => '参数保存成功',
                'data' => [
                    'param_id' => $paramId,
                    'param_name' => $paramName
                ]
            ]);
            
        } catch (\Exception $e) {
            Db::rollBack();
            Log::error("Failed to save custom test parameters: " . $e->getMessage());
            return json(['code' => 500, 'msg' => '保存参数失败']);
        }
    }
    
    /**
     * 获取自定义测试参数
     */
    public function getCustomParams(Request $request)
    {
        $userId = $request->userId;
        $appId = $request->get('app_id');
        $paramName = $request->get('param_name', 'default');
        
        try {
            $param = Db::table('gf_test_custom_params')
                ->where('user_id', $userId)
                ->where('app_id', $appId)
                ->where('param_name', $paramName)
                ->first();
                
            if (!$param) {
                return json([
                    'code' => 404,
                    'msg' => '未找到参数配置'
                ]);
            }
            
            return json([
                'code' => 200,
                'msg' => '获取参数成功',
                'data' => [
                    'param_id' => $param->id,
                    'param_name' => $param->param_name,
                    'params' => json_decode($param->params, true),
                    'created_at' => $param->created_at,
                    'updated_at' => $param->updated_at
                ]
            ]);
            
        } catch (\Exception $e) {
            Log::error("Failed to get custom test parameters: " . $e->getMessage());
            return json(['code' => 500, 'msg' => '获取参数失败']);
        }
    }
    
    /**
     * 获取用户的所有自定义参数列表
     */
    public function getCustomParamsList(Request $request)
    {
        $userId = $request->userId;
        $appId = $request->get('app_id');
        
        try {
            $query = Db::table('gf_test_custom_params')
                ->where('user_id', $userId);
                
            if ($appId) {
                $query->where('app_id', $appId);
            }
            
            $params = $query
                ->orderBy('updated_at', 'desc')
                ->get();
                
            $result = [];
            foreach ($params as $param) {
                $result[] = [
                    'param_id' => $param->id,
                    'param_name' => $param->param_name,
                    'app_id' => $param->app_id,
                    'params_summary' => $this->summarizeParams(json_decode($param->params, true)),
                    'created_at' => $param->created_at,
                    'updated_at' => $param->updated_at
                ];
            }
            
            return json([
                'code' => 200,
                'msg' => '获取参数列表成功',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            Log::error("Failed to get custom test parameters list: " . $e->getMessage());
            return json(['code' => 500, 'msg' => '获取参数列表失败']);
        }
    }
    
    /**
     * 删除自定义参数
     */
    public function deleteCustomParams(Request $request)
    {
        $userId = $request->userId;
        $paramId = $request->post('param_id');
        
        if (empty($paramId)) {
            return json(['code' => 400, 'msg' => '参数ID不能为空']);
        }
        
        try {
            $result = Db::table('gf_test_custom_params')
                ->where('user_id', $userId)
                ->where('id', $paramId)
                ->delete();
                
            if ($result) {
                Log::info("Custom test parameters deleted", [
                    'user_id' => $userId,
                    'param_id' => $paramId
                ]);
                
                return json([
                    'code' => 200,
                    'msg' => '参数删除成功'
                ]);
            } else {
                return json([
                    'code' => 404,
                    'msg' => '未找到要删除的参数'
                ]);
            }
            
        } catch (\Exception $e) {
            Log::error("Failed to delete custom test parameters: " . $e->getMessage());
            return json(['code' => 500, 'msg' => '删除参数失败']);
        }
    }
    
    /**
     * 测试参数传递
     */
    public function testParamTransmission(Request $request)
    {
        $userId = $request->userId;
        $appId = $request->post('app_id');
        $params = $request->post('params');
        $testType = $request->post('test_type', 'share_link'); // share_link, sdk_transmission, persistence
        
        if (empty($appId) || empty($params)) {
            return json(['code' => 400, 'msg' => '应用ID和参数不能为空']);
        }
        
        try {
            // 获取应用信息
            $app = Db::table('gf_apps')
                ->where('id', $appId)
                ->where('user_id', $userId)
                ->first();
                
            if (!$app) {
                return json(['code' => 404, 'msg' => '未找到应用']);
            }
            
            // 模拟参数传递测试
            $result = [];
            
            switch ($testType) {
                case 'share_link':
                    $result = $this->testShareLinkTransmission($app, $params);
                    break;
                    
                case 'sdk_transmission':
                    $result = $this->testSDKTransmission($app, $params);
                    break;
                    
                case 'persistence':
                    $result = $this->testParamPersistence($app, $params);
                    break;
                    
                default:
                    return json(['code' => 400, 'msg' => '无效的测试类型']);
            }
            
            // 记录测试日志
            Db::table('gf_test_logs')->insert([
                'user_id' => $userId,
                'app_id' => $appId,
                'test_type' => $testType,
                'test_params' => json_encode($params),
                'test_result' => json_encode($result),
                'status' => $result['success'] ? 'success' : 'failed',
                'created_at' => date('Y-m-d H:i:s')
            ]);
            
            return json([
                'code' => 200,
                'msg' => '测试完成',
                'data' => $result
            ]);
            
        } catch (\Exception $e) {
            Log::error("Failed to test parameter transmission: " . $e->getMessage());
            return json(['code' => 500, 'msg' => '测试失败']);
        }
    }
    
    /**
     * 测试分享链接参数传递
     */
    private function testShareLinkTransmission($app, $params)
    {
        try {
            // 生成分享链接
            $baseUrl = config('app.url', 'https://example.com');
            $shareUrl = $baseUrl . '/landing/' . $app->appkey;
            
            // 添加参数到URL
            $queryParams = http_build_query($params);
            $fullUrl = $shareUrl . '?' . $queryParams;
            
            // 验证URL长度
            $urlLength = strlen($fullUrl);
            $maxLength = 2000; // 浏览器URL长度限制
            
            return [
                'success' => true,
                'test_type' => 'share_link',
                'share_url' => $fullUrl,
                'url_length' => $urlLength,
                'within_limit' => $urlLength <= $maxLength,
                'params_encoded' => $queryParams,
                'message' => $urlLength <= $maxLength ? '分享链接生成成功' : 'URL长度可能超出浏览器限制'
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'test_type' => 'share_link',
                'error' => $e->getMessage(),
                'message' => '分享链接生成失败'
            ];
        }
    }
    
    /**
     * 测试SDK参数传递
     */
    private function testSDKTransmission($app, $params)
    {
        try {
            // 模拟SDK参数传递过程
            $encodedParams = json_encode($params);
            $paramLength = strlen($encodedParams);
            $maxParamLength = 4096; // SDK参数长度限制
            
            // 验证参数格式
            $isValidJson = json_decode($encodedParams) !== null;
            
            return [
                'success' => $isValidJson && $paramLength <= $maxParamLength,
                'test_type' => 'sdk_transmission',
                'params_json' => $encodedParams,
                'params_length' => $paramLength,
                'within_limit' => $paramLength <= $maxParamLength,
                'json_valid' => $isValidJson,
                'message' => $isValidJson ? ($paramLength <= $maxParamLength ? 'SDK参数传递测试通过' : '参数长度超出SDK限制') : '参数格式无效'
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'test_type' => 'sdk_transmission',
                'error' => $e->getMessage(),
                'message' => 'SDK参数传递测试失败'
            ];
        }
    }
    
    /**
     * 测试参数持久化
     */
    private function testParamPersistence($app, $params)
    {
        try {
            // 模拟参数保存和读取过程
            $original = json_encode($params);
            
            // 模拟保存到数据库
            $saved = json_encode($params);
            
            // 模拟从数据库读取
            $retrieved = json_decode($saved, true);
            
            // 比较原始参数和读取参数
            $match = json_encode($params) === json_encode($retrieved);
            
            return [
                'success' => $match,
                'test_type' => 'persistence',
                'original' => $params,
                'retrieved' => $retrieved,
                'match' => $match,
                'message' => $match ? '参数持久化测试通过' : '参数保存和读取不一致'
            ];
            
        } catch (\Exception $e) {
            return [
                'success' => false,
                'test_type' => 'persistence',
                'error' => $e->getMessage(),
                'message' => '参数持久化测试失败'
            ];
        }
    }
    
    /**
     * 参数摘要
     */
    private function summarizeParams($params)
    {
        if (!is_array($params) || empty($params)) {
            return '无参数';
        }
        
        $keys = array_keys($params);
        $count = count($keys);
        
        if ($count <= 3) {
            return implode(', ', $keys);
        } else {
            return implode(', ', array_slice($keys, 0, 3)) . ' ... (共' . $count . '个)';
        }
    }
}